package cn.springboot.erp.service.impl;

import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.SalesOrders;
import cn.springboot.erp.mapper.SalesOrdersMapper;
import cn.springboot.erp.vo.ShipmentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.springboot.erp.entity.Shipments;
import cn.springboot.erp.service.ShipmentsService;
import cn.springboot.erp.mapper.ShipmentsMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author asus
* @description 针对表【shipments】的数据库操作Service实现
* @createDate 2024-05-12 10:14:04
*/
@Service
public class ShipmentsServiceImpl extends ServiceImpl<ShipmentsMapper, Shipments>
    implements ShipmentsService{

    @Resource
    private SalesOrdersMapper salesOrdersMapper;
    @Override
    public ResponseResult listPage(QueryParams<Shipments> queryParams) {
        Integer page = queryParams.getPage();
        String trackingNumber = queryParams.getSearchParams().getTrackingNumber();
        Integer limit = queryParams.getLimit();

        Page<Shipments> shipmentsPage = new Page<>(page, limit);
        LambdaQueryWrapper<Shipments> lambda = new QueryWrapper<Shipments>().lambda();
        lambda.eq(StringUtils.isNotBlank(trackingNumber),Shipments::getTrackingNumber,trackingNumber);
        baseMapper.selectPage(shipmentsPage,lambda);

        List<ShipmentVO> vo = shipmentsPage.getRecords().stream().map(shipment -> {
            ShipmentVO shipmentVO = new ShipmentVO();
            BeanUtils.copyProperties(shipment, shipmentVO);

            Integer orderId = shipment.getOrderId();
            SalesOrders salesOrders = salesOrdersMapper.selectById(orderId);
            shipmentVO.setOrderNumber(salesOrders.getOrderNumber());
            return shipmentVO;
        }).collect(Collectors.toList());
        return ResponseResult.Success()
                .data("total",shipmentsPage.getTotal())
                .data("vo",vo);
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        Shipments shipments = baseMapper.selectById(id);
        if (shipments.getStatus()==0){
            return ResponseResult.Fail().msg("运输中，暂时不能删除");
        }
        baseMapper.deleteById(id);
        return ResponseResult.Success().msg("删除成功");
    }
}




